package com.lvyq.qrobot.server;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.lvyq.qrobot.common.UrlConstant;
import com.lvyq.qrobot.locadata.OrderCode;
import com.lvyq.qrobot.locadata.OrderContent;
import com.lvyq.qrobot.model.other.HoroScope;
import com.lvyq.qrobot.model.receive.ReceiveMsg;
import com.lvyq.qrobot.model.send.SendParam;
import com.lvyq.qrobot.util.ChuanYueUtil;
import com.lvyq.qrobot.util.CommonUtil;
import com.lvyq.qrobot.util.HttpClientUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

/**
 * @author lvyq 便民
 * @version 1.0
 * Create by 2024-05-31 10:52
 */
public class BianMinServer {

    //笑话数量
    public static final Integer JOKE_COUNT=49;

    /**
     * @description 讲笑话
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-05-31 10:55
     */
    public static void tellJokes(SendParam param, ReceiveMsg vo) {
        //讲笑话
        if (OrderCode.TELL_JOKES.name.equals(vo.message)){
            String content=OrderCode.TELL_JOKES.content.replace(
                    "{1}", UrlConstant.Audio_JOKE+ CommonUtil.randomNum(JOKE_COUNT)+".mp3"
            );
            param.setMessage(content);
            HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
        }
    }

    /**
     * @description 点歌
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-05-31 10:58
     */
    public static void singASong(SendParam param, ReceiveMsg vo) {
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm( UrlConstant.RAND_MUSIC, null));
        String musicUrl = mav.getJSONObject("data").get("url").toString();
        String id = musicUrl.split("=")[1];
        param.setMessage(OrderCode.SING_A_SONG.content.replace("{1}",id));
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 历史今天
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-05-31 11:01
     */
    public static void historyToday(SendParam param, ReceiveMsg vo) {
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(UrlConstant.HISTORY_TODAY, null));
        JSONArray result = mav.getJSONArray("result");
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < result.size(); i++) {
            JSONObject con = (JSONObject) result.get(i);
            buffer.append(con.get("year")+"   "+con.get("title")+"\n");
        }
        param.setMessage(buffer.toString());
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 热量查询
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-05-31 11:05
     */
    public static void foodHead(SendParam param, ReceiveMsg vo) {
            String msg = vo.message;
            msg = msg.replace("热量","");
            String url = UrlConstant.FOOD_HEAD.replace("{1}", msg);
            String content = HttpClientUtil.doGetForm(url, null);
            JSONObject mav = JSONUtil.parseObj(content);
            JSONArray result = mav.getJSONArray("result");
            StringBuffer buffer = new StringBuffer();
            String returnMsg = OrderCode.FOOD_HEAT.content;
            int count = 1;
            for (int i = 0; i < result.size(); i++) {
                JSONObject con = (JSONObject) result.get(i);
                if (count>5){break;}
                try {
                    buffer.append(
                            returnMsg.replace("{1}",con.getStr("img"))
                                    .replace("{2}",con.get("name").toString())
                                    .replace("{3}",con.getStr("heat"))
                                    .replace("{4}",con.getStr("desc"))
                    );

                }catch (Exception e){
                    System.out.println("热量查询数据异常");
                }
                count++;
            }
            param.setMessage(buffer.toString());
            HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 日历
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-05-31 13:56
     */
    public static void calendar(SendParam param, ReceiveMsg vo) {
        String content = HttpClientUtil.doGetForm(UrlConstant.MOYU_CAL, null);
        JSONObject mav = JSONUtil.parseObj(content);
        String url = mav.get("url").toString();
        param.setMessage(OrderCode.CALENDAR.content.replace("{1}",url));
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 运势
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-07-08 12:01
     */
    public static void horoscope(SendParam param, ReceiveMsg vo) {
        String message = vo.message.trim();
        String horoscopeUrl = UrlConstant.HOROSCOPE;
        //星座
        String[] xz = message.split("座");
        String xzname = xz[0]+"座";
        String sco= CommonUtil.scorpioNameConvert(xzname);
        String time = "today";
        time = CommonUtil.scorpioTimeConvert(xz[1]);
        horoscopeUrl=horoscopeUrl.replace("TIME",time).replace("SCORPIO",sco);
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(horoscopeUrl, null));
        String data = mav.get("data").toString();
        HoroScope horoScope = JSONUtil.toBean(data, HoroScope.class);
        //简介
        StringBuffer buffer = new StringBuffer();
        buffer.append("[CQ:at,qq="+vo.userId+"]\n");
        buffer.append(horoScope.getTitle()+"-"+horoScope.getType()+"("+horoScope.getTime()+")\n");
        buffer.append("\uD83C\uDF89"+horoScope.getShortcomment()+"\uD83C\uDF89\n");
        if (horoScope.getLuckycolor()!=null){
            buffer.append("\uD83C\uDFA8幸运颜色:"+horoScope.getLuckycolor()+"\n");
            buffer.append("\uD83D\uDD22幸运数字:"+horoScope.getLuckynumber()+"\n");
            buffer.append("✴️速配星座:"+horoScope.getLuckyconstellation()+"\n");
        }
        buffer.append("\uD83C\uDF39==========\uD83C\uDF39\n");
        buffer.append("✨️宜:"+horoScope.getTodo().getYi()+"\n");
        buffer.append("✨️忌:"+horoScope.getTodo().getJi()+"\n");
        //详情
        buffer.append("\uD83C\uDF39==========\uD83C\uDF39\n");
        buffer.append("整体运势:"+CommonUtil.changeStart(horoScope.getFortune().getAll())+"\n"+horoScope.getFortunetext().getAll()+"\n");
        buffer.append("爱情运势:"+CommonUtil.changeStart(horoScope.getFortune().getLove())+"\n"+horoScope.getFortunetext().getLove()+"\n");
        buffer.append("事业运势:"+CommonUtil.changeStart(horoScope.getFortune().getWork())+"\n"+horoScope.getFortunetext().getWork()+"\n");
        buffer.append("财富运势:"+CommonUtil.changeStart(horoScope.getFortune().getMoney())+"\n"+horoScope.getFortunetext().getMoney()+"\n");
        buffer.append("健康运势:"+CommonUtil.changeStart(horoScope.getFortune().getHealth())+"\n"+horoScope.getFortunetext().getHealth()+"\n");
        param.setMessage(buffer.toString());

        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    public static void qqSong(SendParam param, ReceiveMsg vo) {
        String message = vo.message;
        String sname = message.split("点歌")[1];
        String randMusic = UrlConstant.QQ_SONG.replace("MSG",sname).replace("N","1");
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(randMusic , null));
        String songname = mav.getJSONObject("data").get("songname").toString();
        String src = mav.getJSONObject("data").get("src").toString();
        String songurl = mav.getJSONObject("data").get("songurl").toString();
        String name = mav.getJSONObject("data").get("name").toString();
        String cover = mav.getJSONObject("data").get("cover").toString();

        String content = OrderCode.QQ_SONG.content;
        content=content.replace("URL",songurl)
                        .replace("AUDIO",src)
                        .replace("TITLE",songname)
                        .replace("SINGER",name)
                        .replace("IMG",cover);
        param.setMessage(content);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 对话
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-07-09 9:04
     */
    public static void chat(SendParam param, ReceiveMsg vo) {
        String message = vo.message;
        String msg = message.split("\\[CQ:at,qq=1482996173\\]")[1].trim();
       String replace=qingyunkeChat(msg, vo);






        param.setMessage(replace);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);

    }

    /**
     * @description婧枫对话
     * @author lvyq
     * @param[1] msg
     * @throws
     * @return String
     * @time 2024-07-11 15:57
     */
    private static String qianfengChat(String msg,ReceiveMsg vo) {
        String chatUrl = UrlConstant.CHAT_QF.replace("MSG",msg);
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(chatUrl, null));
        String answer = mav.getJSONObject("data").getStr("output");
        System.out.println("聊天回话>>>"+answer);
        String replace = OrderCode.CHAT.content.replace("{1}", vo.userId.toString()).replace("{2}", answer)
                .replace("{3}",vo.messageId.toString());
        return replace;
    }


    /**
     * @description 图灵
     * @author lvyq
     * @param[1] msg
     * @param[2] vo
     * @throws
     * @return String
     * @time 2024-07-11 16:00
     */
    private static String tulingChat(String msg,ReceiveMsg vo) {
        String chatUrl = UrlConstant.CHAT_TL.replace("MSG",msg);
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(chatUrl, null));
         String answer = mav.getJSONObject("data").getStr("answer");
        System.out.println("聊天回话>>>"+answer);
        String replace = OrderCode.CHAT.content.replace("{1}", vo.userId.toString()).replace("{2}", answer)
                .replace("{3}",vo.messageId.toString());
        return replace;
    }

    /**
     * @description 青云客
     * @author lvyq
     * @param[1] msg
     * @param[2] vo
     * @throws
     * @return String
     * @time 2024-07-11 16:01
     */
    private static String qingyunkeChat(String msg,ReceiveMsg vo) {
        String chatUrl = UrlConstant.CHAT_QYK.replace("MSG",msg);
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(chatUrl, null));
        String answer = mav.getStr("content");
        answer=answer.replace("{br}","\n");
        System.out.println("聊天回话>>>"+answer);
        String replace = OrderCode.CHAT.content.replace("{1}", vo.userId.toString()).replace("{2}", answer)
                .replace("{3}",vo.messageId.toString());
        return replace;
    }
    /**
     * @description 懒大王
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws
     * @time 2024-07-09 10:18
     */
    public static void ldw(SendParam param, ReceiveMsg vo) {
        String s = HttpClientUtil.doGetForm(UrlConstant.LDW, null);
        String msg = "[CQ:video,file="+s+"]";
        param.setMessage(msg);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 舔狗日记
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws

     * @time 2024-07-09 14:58
     */
    public static void tgrj(SendParam param, ReceiveMsg vo) {
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(UrlConstant.TGRJ, null));
        String msg = mav.getJSONObject("result").getStr("content");
        param.setMessage(msg);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    public static void shf(SendParam param, ReceiveMsg vo) {
        JSONObject mav = JSONUtil.parseObj(HttpClientUtil.doGetForm(UrlConstant.SHF, null));

        String question = mav.getStr("question");
        String answer = mav.getStr("answer");
        param.setMessage(question+"\n"+answer);
        HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
    }

    /**
     * @description 鬼故事
     * @author lvyq
     * @param[1] param
     * @param[2] vo
     * @throws

     * @time 2024-07-10 11:01
     */
    public static void ggs(SendParam param, ReceiveMsg vo) {
        String randomNum = CommonUtil.randomGenerator(1, 999);
        String res="";

        try {
            res=ChuanYueUtil.sendGet("http://www.guiguaiwu.com/html/dpggs_1529_23"+randomNum+".html");
            Document parse = Jsoup.parse(res);
            String title = parse.getElementsByTag("h1").text();
          //  System.out.println("title = " + title);
            Element myContent = parse.getElementById("MyContent");
            Elements elements = myContent.getElementsByTag("p");
            StringBuffer buffer = new StringBuffer();
            buffer.append("\uD83D\uDCD6"+title+"\uD83D\uDCD6");
            for (int i = 0; i < elements.size(); i++) {
                Element element = elements.get(i);
                String img2 = element.getElementsByTag("img").attr("src");
                if (img2!=null && !img2.equals("") ){
                    System.out.println("ssss>>>"+img2);
                    String s = HttpClientUtil.imgWrite(img2);
                    System.out.println("s = " + s);
                    buffer.append("[CQ:image,file="+s+"]");
                }

                //  System.out.println("text = " +element.text());
                buffer.append(element.text()+"\n");

            }
           // System.out.println("结果："+buffer.toString());
            System.out.println(buffer.length());
            param.setMessage(buffer.toString());
            HttpClientUtil.doPostJson(UrlConstant.send_group_msg,param);
        }catch (Exception e){
                ggs(param,vo);
        }

    }
}
